package com.waymap.utils;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.waymap.domain.ItemInventorys;
import com.waymap.domain.Items;
import com.waymap.mapper.ItemInventorysMapper;
import com.waymap.mapper.ItemsMapper;
import com.waymap.mapper.LocationsMapper;
import com.waymap.mapper.TransactionItemInventoryDetailsMapper;
import com.waymap.mapper.TransactionItemsMapper;
import com.waymap.mapper.TransactionsMapper;
import com.waymap.service.UserService;

@Component
public class CommonService {
	@Resource
    private TransactionItemsMapper transactionItemsMapper;
    @Resource
    private TransactionItemInventoryDetailsMapper transactionItemInventoryDetailMapper;
    @Resource
    private TransactionsMapper transactionsMapper;
    @Resource
    private LocationsMapper locationsMapper;
    @Resource
    private ItemsMapper itemsMapper;
    @Autowired
    private UserService userService;
    @Resource
    private ItemInventorysMapper itemInventorysMapper;
    
    /**
	 * by vincent mai
	 * @param itemId 产品id
	 * @param accountId 客户账号id
	 * @param binName 库位名，开了库位的产品必须填库位，不开库位的则该值为空
	 * @param lotNumber 批次号，批次产品须填，非批次产品该值为空
	 * @param qty 数量，出库时为负数，入库时为正数
	 * 更新WMS库存数据，根据产品的类型
	 * L为批次不开库位的产品
	 * IB为开库位非批次产品
	 * IB为开库位非批次产品
	 * LB为开库位的批次产品
	 */
    @Transactional(rollbackFor = Exception.class)
	public void updateItemInventory(int location,int itemId, String accountId,String binName,String lotNumber,int qty) {
		Items item = new Items();
		item.setAccountId(accountId);
		item.setItemId(itemId);
		item = itemsMapper.selectOne(item);
		
		ItemInventorys iinv = new ItemInventorys();
		iinv.setAccountId(accountId);
		iinv.setItemId(itemId);
		iinv.setLocationId(location);
		if("L".equals(item.getItemType())) {
			iinv.setLotNumber(lotNumber);
		} else if("LB".equals(item.getItemType())) {
			iinv.setLotNumber(lotNumber);
			iinv.setBinName(binName);
		} else if("IB".equals(item.getItemType())) {
			iinv.setBinName(binName);
		}
		ItemInventorys iinvExist = itemInventorysMapper.selectOne(iinv);
		if(iinvExist == null) {
			iinv.setQuantityAvailable(qty);
			itemInventorysMapper.insert(iinv);
		} else {
			iinvExist.setQuantityAvailable(iinvExist.getQuantityAvailable()+qty);
			itemInventorysMapper.updateByPrimaryKey(iinvExist);
		}
	}
}
